using Prism.Mvvm;
using Prism.Commands;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using CPlatePrintSys.Application.Services;
using CPlatePrintSys.Domain.Models;
using System.Collections.Generic;

namespace CPlatePrintSys.Win.ViewModels
{
    public class StreamShipAddOrEditViewModel : BindableBase
    {
        private readonly IShipConfigService _service;
        public ObservableCollection<MotherShip> MotherShips { get; }
        public MotherShip SelectedMotherShip { get; set; }
        public string StreamShipNo { get; set; }
        public DelegateCommand SaveCommand { get; }
        public DelegateCommand CancelCommand { get; }
        private readonly StreamShip _editingStreamShip;

        public StreamShipAddOrEditViewModel(IShipConfigService service, List<MotherShip> motherShips, StreamShip editingStreamShip = null)
        {
            _service = service;
            MotherShips = new ObservableCollection<MotherShip>(motherShips);
            _editingStreamShip = editingStreamShip;
            if (editingStreamShip != null)
            {
                StreamShipNo = editingStreamShip.ShipNo;
                SelectedMotherShip = motherShips.FirstOrDefault(m => m.Id == editingStreamShip.MotherShipId);
            }
            SaveCommand = new DelegateCommand(OnSave);
            CancelCommand = new DelegateCommand(OnCancel);
        }

        private async void OnSave()
        {
            if (SelectedMotherShip == null || string.IsNullOrWhiteSpace(StreamShipNo))
            {
                MessageBox.Show("请选择母船并输入流用船号！");
                return;
            }
            if (_editingStreamShip == null)
            {
                await _service.AddStreamShipAsync(StreamShipNo.Trim().ToUpper(), SelectedMotherShip.Id);
            }
            else
            {
                await _service.DeleteStreamShipAsync(_editingStreamShip.Id);
                await _service.AddStreamShipAsync(StreamShipNo.Trim().ToUpper(), SelectedMotherShip.Id);
            }
            CloseDialog(true);
        }

        private void OnCancel() => CloseDialog(false);

        private void CloseDialog(bool? result)
        {
            // Fix: Access Application.Current correctly
            var application = System.Windows.Application.Current; // Ensure the correct namespace is used
            if (application != null)
            {
                var window = application.Windows.OfType<Window>().FirstOrDefault(w => w.DataContext == this);
                if (window != null)
                    window.DialogResult = result;
            }
        }
    }
} 